<?php

namespace App\Http\Model;

use App\User;
use Fenos\Notifynder\Facades\Notifynder;
use Illuminate\Database\Eloquent\Model;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Image;
use Illuminate\Support\Facades\Log;

class WechatMessage extends Model
{
    public function analyseReceivedMessageType($message,$app){
        switch ($message->MsgType) {
            case 'event':
                # 事件消息...
                return $this->analyseReceivedEventMessage($message,$app);
            case 'text':
                # 文字消息...
                return $this->analyseReceiveTextMessage($message);
            case 'image':
                # 图片消息...
                break;
            case 'voice':
                # 语音消息...
                break;
            case 'video':
                # 视频消息...
                break;
            case 'location':
                # 坐标消息...
                break;
            case 'link':
                # 链接消息...
                break;
            // ... 其它消息
            case 'transfer_customer_service':
                //消息转发到客服

                break;
            default:
                # code...
                break;
        }
    }
    /**
     * 发送文本消息
     * @param $content  文本内容
     * @return Text
     */

    public function sendTextMessage($content){
        return new Text(['content' => $content]);
    }

    public function sendImageMessage($mediaId){
        return  new Image(['media_id' => $mediaId]);
    }

    /**
     * 发送自定义图文消息
     */
    public function sendCustomSendNewsMessage($toUser,$fromUser,$dataList) {

        if(!is_array($dataList) ||  ($count = count($dataList)) == 0){
            die('need array ');
        }
        $format = '<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>%s</ArticleCount><Articles>';
        foreach ($dataList as $v){
            $format .= '<item><Title><![CDATA['.$v['title'].']]></Title><Description><![CDATA['.$v['description'].']]></Description><PicUrl><![CDATA['.$v['picurl'].']]></PicUrl><Url><![CDATA['.$v['url'].']]></Url></item>';
        }

        $format .= ' </Articles></xml>';
        $timestamp = time();
        return sprintf($format, $toUser, $fromUser, $timestamp, $count);
    }


    //关键字处理
    public  function analyseReceiveTextMessage($message){
        switch ($message->Content){
            case '1':
                return $this->sendTextMessage("♥e美平台线下体验馆♥
地址：银辉摩天360大厦A座2207室(苏宁广场左边，三阳百盛的通灵翠钻旁边)
电话：13861845966

♥G梵希护肤造型♥
地址：无锡东亭锡州东路35号（汉庭酒店隔壁）
电话：13861845966");
                break;
            case '2':
                return $this->sendTextMessage("在线预约美容、美发、美体、养生服务，请戳链接：http://www.520mrw.com/sellerDetail/473624224

商城预约美容项目，好处大大的：
♥网上商城预约，到店可减免多项费用，优惠超级多；
♥获得优先服务权，获得优先选择技师权，省去了到店排队之苦；
♥提前了解体验店内各项产品信息，选择好之后到店直奔主题，省时省事！");
                break;
            case 3:
                return $this->sendTextMessage(11);
                break;
            default:
                //消息转发到客服
                return new \EasyWeChat\Message\Transfer();
                break;
        }

    }
    private function analyseReceivedEventMessage($message,$app){

        switch ($message->Event){
            case 'subscribe':
                return $this->subscribe($message);
            case 'unsubscribe':
                //取消关注、订阅
                return $this->unSubscribe($message);
                break;
            case 'SCAN':
                if(isset($message->EventKey)){ //扫码关注
                    $keyArray = explode("_", $message->EventKey);
                    if(count($keyArray) == 2){
                        $this->sendTextMessage("您已经关注啦！");
                    }
                }else {

                }

                break;
            case 'LOCATION':
                //上报地理位置事件
                break;
            case 'CLICK':
                //自定义菜单事件
                switch ($message->EventKey){
                    case 'V1001_my_qrcode':
                        try{

                            $staff  = $app->staff;

                            $staff->message($this->sendTextMessage("美友您好,恭喜您的二维码已生成，邀请您的朋友扫码即可关注我们。友情提醒：二维码有效期为3天，到期前请重新生成，谢谢 。"))->to($message->FromUserName)->send();

                            //return $this->sendTextMessage( $qrCodeImage);
                           return $this->sendImageMessage( (new User())->genQRCode($message->FromUserName,3,$app,true));
                        }catch (\Exception $e){
                            return $this->sendTextMessage($e);
                        }
                    default:
                        break;
                }
                break;
            case 'VIEW':
                //点击菜单跳转链接时的事件推送
                break;
            default:
                break;
        }
    }

    private function subscribe($message){
        $pid = 0;
        $ppid = 0;
        $pppid = 0;
        if(isset($message->EventKey)){ //扫码关注
            $keyArray = explode("_", $message->EventKey);
            $pid = $keyArray[1];
            $pUser = User::find($pid);
            if($pUser){
                $ppid = $pUser->pid;
                $pppid = $pUser->ppid;
            }
        }

        $User = new User();
        $app_name = env("APP_NAME");
        if(!$User->checkExistsByOpenid($message->FromUserName)){
            $data['openid'] = $message->FromUserName;
            $data['name'] =  "wx_".$message->FromUserName;
            $data['addtime'] = time();
            $data['subscribe'] = 2;
            $data['pid'] = $pid;
            $data['ppid'] = $ppid;
            $data['pppid'] = $pppid;
            $uid = $User->addUser($data);
            $from_user = $User->getUserNickName($uid);
            Notifynder::category('user.following')->from(0)->to($pid)->url("/Message/index")->extra(compact('from_user'))->send();
            Notifynder::category('user.following')->from(0)->to($ppid)->url("/Message/index")->extra(compact('from_user'))->send();
            Notifynder::category('user.following')->from(0)->to($pppid)->url("/Message/index")->extra(compact('from_user'))->send();
            (new Distribution())->addUser($uid);
        }else{

            $subscribe = User::where("openid",'=',$message->FromUserName)->first();

            if($subscribe->password != '')
                User::where("openid",'=',$message->FromUserName)->update(['subscribe'=>1,'pid'=>$pid]);
            else
                User::where("openid",'=',$message->FromUserName)->update(['subscribe'=>2,'pid'=>$pid]);
            $uid = $subscribe->id;

        }
        Notifynder::category('user.subscribe')->from(0)->to($uid)->url("/Message/index")->extra(compact('app_name'))->send();

        return $this->sendTextMessage("♥亲爱的，感谢关注e美平台!
                
♥e美平台为您提供多方位的优质美容服务，集造型、护肤、SPA、养生于一体。

客服电话：0510-85056591
客服QQ：2930894756

♥回复“1”，查看各门店地址、电话!
♥回复“2”，在线预约美容、美发、减肥、养生服务！");

    }

    public function unSubscribe($message) {
        $app_name = env("APP_NAME");
        $uid = (new User())->getUserIdByOpenId($message->FromUserName);
        Notifynder::category('user.unsubscribe')->from(0)->to($uid)->url("/Message/index")->extra(compact('app_name'))->send();
        return User::where("openid",'=',$message->FromUserName)->update(['subscribe'=>0]);
    }


}
